﻿using ConfExpert.Forms.Base;
using DevExpress.Utils;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraPivotGrid;
using DevTeam;

using System;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.Planlama
{
    public partial class Kalite2 : XForm
    {
        public Kalite2()
        {
            InitializeComponent();
        }

        private void Kalite2_Load(object sender, EventArgs e)
        {
            //this.panelControl1.Visible = false;
            deStart.EditValue = new DateTime(2015, 1, 1);
            deEnd.EditValue = new DateTime(2015, DateTime.Today.Month, 1);
            //chkBitis.Checked = true;
            deEnd.Visibility =  DevExpress.XtraBars.BarItemVisibility.Always;

            RefreshData();
            ExpandCollapse(splitContainerControl1, AcKapa.Collapse);
            btnExport.ItemClick += btnExport_ItemClick;

            pvg.OptionsPrint.PrintColumnHeaders = DevExpress.Utils.DefaultBoolean.False;
            pvg.OptionsPrint.PrintDataHeaders = DevExpress.Utils.DefaultBoolean.False;
            pvg.OptionsPrint.PrintFilterHeaders = DevExpress.Utils.DefaultBoolean.False;
            pvg.OptionsPrint.MergeRowFieldValues = false;
            pvg.OptionsPrint.MergeColumnFieldValues = false;
            pvg.OptionsView.ShowFilterHeaders = false;
            pvg.CustomAppearance+=pvg_CustomAppearance;
            //pvg.CustomUnboundFieldData+=pvg_CustomUnboundFieldData;
            //pvg.OptionsView.ShowFilterSeparatorBar = 

            ((RepositoryItemComboBox)cmbLayout.Edit).Items.AddRange(new object[] { "Atelye vs. Hata", "Atelye vs. Customer", "Atelye vs. Article", "Atelye vs. ProductId", "Customer vs. Hata", "Customer vs. Artikel", "Customer vs. ProductId" });

            cmbLayout.EditValueChanged += cmbLayout_EditValueChanged;
            ((RepositoryItemComboBox)cmbLayout.Edit).TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
            cmbLayout.EditValue = "Atelye vs. Hata";

            deStart.EditValueChanged += deMonth_EditValueChanged;
            deEnd.EditValueChanged += deMonth_EditValueChanged;
            //chkBitis.CheckedChanged += chkBitis_CheckedChanged;

            chkSort.CheckedChanged += chkSort_CheckedChanged;

        }

        void btnExport_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ExportPivot(pvg);
        }

        void chkSort_CheckedChanged(object sender, EventArgs e)
        {
            cmbLayout_EditValueChanged(null, null);
        }

        //void chkBitis_CheckedChanged(object sender, EventArgs e)
        //{
        //    deEnd.Visibility = chkBitis.Checked ? DevExpress.XtraBars.BarItemVisibility.Always : DevExpress.XtraBars.BarItemVisibility.Never ;
        //    if (!chkBitis.Checked) deEnd.EditValue = null;
        //    RefreshData();
        //}

        void deMonth_EditValueChanged(object sender, EventArgs e)
        {
            RefreshData();
        }



        void cmbLayout_EditValueChanged(object sender, EventArgs e)
        {
            //new field - toplam tutar  (metre x fiyat+dvz cinsi)
            //.Width = 40;  .Visible = true;
            //    fld.SummaryType = DevExpress.Data.PivotGrid.PivotSummaryType.Sum;

            pvg.BeginUpdate();
            pvg.Groups.Clear();
            pvg.Fields.Clear();

            //AddNewField(pvg, "Tarih", PivotArea.FilterArea).FieldEdit = new RepositoryItemDateEdit();
            //AddNewField(pvg, "Hata", PivotArea.FilterArea).FieldName = "HataF";
            //pvg.Fields["HataF"].FieldEdit = RI(Rp.Hata);
            //AddNewField(pvg, "Etki", PivotArea.FilterArea);

            ((RepositoryItemDateEdit)deStart.Edit).VistaCalendarViewStyle =
            ((RepositoryItemDateEdit)deEnd.Edit).VistaCalendarViewStyle = DevExpress.XtraEditors.VistaCalendarViewStyle.YearView;

            ((RepositoryItemDateEdit)deStart.Edit).EditMask =
            ((RepositoryItemDateEdit)deStart.Edit).DisplayFormat.FormatString =
            ((RepositoryItemDateEdit)deEnd.Edit).EditMask =
            ((RepositoryItemDateEdit)deEnd.Edit).DisplayFormat.FormatString = "MM/yyyy";
            //deStart.Properties.MinValue = new System.DateTime(2012, 3, 1);

            //AddNewField(pvg, "Yuzde", PivotArea.DataArea);
            AddNewField(pvg, "Adet", PivotArea.DataArea);   //.Caption = "Adet";
            //AddNewField(pvg, "Total", PivotArea.DataArea).Caption = "Topl.";


            //// Create a field with the specified field name.
            //PivotGridField unboundField = pvg.Fields.Add("Yüzde", PivotArea.DataArea);
            //// Specify the type of the field's values.
            //unboundField.UnboundType = DevExpress.Data.UnboundColumnType.Decimal;
            //unboundField.UnboundExpressionMode = UnboundExpressionMode.UseSummaryValues;
            //unboundField.CellFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
            //unboundField.CellFormat.FormatString = "P2";

            //PivotGridField fd = new PivotGridField();
            //fd.FieldName = fd.Caption = "Yüzde";
            //fd.UnboundFieldName = "Yüzde";
            //fd.UnboundExpression = "Adet/Total";
            //fd.UnboundType = DevExpress.Data.UnboundColumnType.Decimal;
            //fd.UnboundExpressionMode = UnboundExpressionMode.UseSummaryValues;
            //fd.CellFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
            //fd.CellFormat.FormatString = "P2";
            //pvg.Fields.Add(fd);
            //fd.SetAreaPosition(PivotArea.DataArea, 2);

            switch (cmbLayout.EditValue.ToStr())
            {
                case "Atelye vs. Hata":
                    AddNewField(pvg, "Atelye", PivotArea.RowArea);
                    AddNewFields(pvg, "Grup", "Hata", PivotArea.ColumnArea);
                    MakeSort("Atelye", "Hata");
                    break;

                case "Atelye vs. Customer":
                    AddNewField(pvg, "Atelye", PivotArea.RowArea);  //.FieldEdit = RI(Rp.Atelye);
                    AddNewField(pvg, "Customer", PivotArea.ColumnArea); //.FieldEdit = RI(Rp.V_Customer);
                    MakeSort("Atelye", "Customer");
                    break;

                case "Atelye vs. Article":
                    AddNewField(pvg, "Atelye", PivotArea.RowArea);
                    AddNewField(pvg, "Artikel", PivotArea.ColumnArea);
                    MakeSort("Artikel", "Atelye");
                    break;

                case "Atelye vs. ProductId":
                    AddNewField(pvg, "Atelye", PivotArea.RowArea);
                    AddNewField(pvg, "ProductId", PivotArea.ColumnArea).FieldEdit = RI(Rp.V_Kumas);
                    MakeSort("Atelye", "ProductId");
                    break;

                case "Customer vs. Hata":
                    AddNewField(pvg, "Customer", PivotArea.RowArea);
                    AddNewFields(pvg, "Grup", "Hata", PivotArea.ColumnArea);
                    //AddNewField(pvg, "Hata", PivotArea.ColumnArea);
                    MakeSort("Customer", "Hata");
                    break;

                case "Customer vs. Artikel":
                    AddNewField(pvg, "Customer", PivotArea.RowArea);
                    AddNewField(pvg, "Artikel", PivotArea.ColumnArea);
                    MakeSort("Customer", "Artikel");
                    break;

                case "Customer vs. ProductId":
                    AddNewField(pvg, "Customer", PivotArea.RowArea);
                    AddNewField(pvg, "ProductId", PivotArea.ColumnArea).FieldEdit = RI(Rp.V_Kumas);
                    MakeSort("Customer", "ProductId");
                    break;
            }

            //foreach (PivotGridField pgf in pvg.Fields)
            //{
            //    pgf.SortOrder = PivotSortOrder.Ascending;
            //    pgf.Options.AllowSort = DevExpress.Utils.DefaultBoolean.True;
            //}
            pvg.EndUpdate();
            pvg.CollapseAll();
            pvg.BestFit();
            //pvg.Fields["Total"].Visible = false;

            pvg.Focus();
        }


        void MakeSort(params string[] strs)
        {
            //https://documentation.devexpress.com/#WindowsForms/CustomDocument5326
            //https://documentation.devexpress.com/#corelibraries/DevExpressXtraPivotGridPivotGridFieldBase_SortBySummaryInfotopic
            //https://documentation.devexpress.com/#windowsforms/DevExpressXtraPivotGridPivotGridControl_CustomFieldSorttopic

            //https://documentation.devexpress.com/#WindowsForms/CustomDocument1954

            //http://stackoverflow.com/questions/569162/how-to-add-a-weighted-average-summary-to-a-devexpress-xtragrid?rq=1

            //https://www.devexpress.com/Support/Center/Question/Details/Q314013
            //https://documentation.devexpress.com/#WindowsForms/DevExpressXtraPivotGridPivotGridControl_CustomCellEdittopic



            foreach (string str in strs)
            {
                pvg.Fields[str].SortBySummaryInfo.Conditions.Clear();
                pvg.Fields[str].SortOrder = chkSort.Checked ? PivotSortOrder.Ascending : PivotSortOrder.Descending;
                pvg.Fields[str].SortBySummaryInfo.Field = pvg.Fields[chkSort.Checked ? strs[0] : "Adet"];

                if (str == "Artikel" || 
                    str == "ProductId")
                {
                    pvg.Fields[str].TopValueCount = 30;
                    pvg.Fields[str].TopValueShowOthers = true;
                    pvg.Fields[str].TopValueType = PivotTopValueType.Absolute;
                }
            }
        }





        void pvg_CustomAppearance(object sender, PivotCustomAppearanceEventArgs e)
        {
            if (e.ColumnValueType == PivotGridValueType.Value && e.RowValueType == PivotGridValueType.Value)
                switch (e.DataField.FieldName)
                {
                    case "AtelyeId":
                        e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);
                        break;

                    //case "Yüzde":
                    //    e.Appearance.BackColor = e.Appearance.BackColor2 = Color.LightBlue;
                    //    break;
                }

            /*

            int deger = e.GetFieldValue(pvg.Fields["Total"]).ToInt();
            if (deger > calcEdit1.Value)
                e.Appearance.BackColor = e.Appearance.BackColor2 = Color.Red;
            else
                e.Appearance.BackColor = e.Appearance.BackColor2 = Color.FromArgb((100 * deger / calcEdit1.Value).ToInt(), Color.Red);
             */
        }
    
             /* 
             * PivotGridField[] fields2 = new PivotGridField[1];
            //pivotGridControl1.Fields["Tarih"].ValueFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
            //pivotGridControl1.Fields["Tarih"].ValueFormat.FormatString = "d";

            PivotGridField fieldYear = new PivotGridField("Tarih", PivotArea.ColumnArea);
            PivotGridField fieldMonth = new PivotGridField("Tarih", PivotArea.ColumnArea);

            pvg.Fields.Add(fieldYear);
            fieldYear.GroupInterval = PivotGroupInterval.DateYear;
            fieldYear.Caption = "Year";
            
            pvg.Fields.Add(fieldMonth);
            fieldMonth.GroupInterval = PivotGroupInterval.DateQuarter;
            fieldMonth.Caption = "Quarter";
            
            fields2[0] = fieldYear;
            //fields2[1] = fieldMonth;

            fields2[0].ExpandedInFieldsGroup = false;
            pvg.Groups.Add(fields2, "Tarih");
            */

        //PivotGridControl.RetrieveFields 


        void AddNewFields(PivotGridControl pgc, string FieldName1, string FieldName2, PivotArea pa)
        {
            PivotGridField[] fields2 = new PivotGridField[2];
            fields2[0] = AddNewField(pgc, FieldName1, pa);
            fields2[1] = AddNewField(pgc, FieldName2, pa);
            //fields2[0].ExpandedInFieldsGroup = false;
            pvg.Groups.Add(fields2, "Hatalar");
        }


        void RefreshData()
        {
            bs = gridView1.Init("GetPLHata3", (deStart.EditValue.ToDate().Month.ToInt()), deStart.EditValue.ToDate().Year.ToInt(),
                deEnd.EditValue.ToDate().Month.ToInt(), deEnd.EditValue.ToDate().Year.ToInt());
            //, chkBitis.Checked
            //gridView1.Columns["Oran"].DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
            //gridView1.Columns["Oran"].DisplayFormat.FormatString = "P1";

            gridView1.FormatAsNumber(0, "Adet");
            gridView1.AddSummary("Adet");
            gridView1.MakeReadOnly();

            InitPivot(pvg, bs);
            gridView1.BestFitColumns();

            //pvg.Cells.Selection = new Rectangle(new Point(0, 0), new Size(1, 1));
        }

        bool PivotInitialized = false;
        void InitPivot(PivotGridControl pvg, BindingSource bs)
        {
            pvg.DataSource = bs;

            if (!PivotInitialized)
            {
                pvg.OptionsCustomization.CustomizationFormStyle = DevExpress.XtraPivotGrid.Customization.CustomizationFormStyle.Excel2007;
                pvg.CellClick += new PivotCellEventHandler(pivotGridControl1_CellClick);
                //pvg.CellSelectionChanged += new EventHandler(pvg_CellSelectionChanged);
                //pvg.FocusedCellChanged += new EventHandler(pvg_FocusedCellChanged);
                pvg.FieldValueDisplayText += new PivotFieldDisplayTextEventHandler(pivotGrid_FieldValueDisplayText);
                pvg.CustomAppearance += new PivotCustomAppearanceEventHandler(pivotGridControl1_CustomAppearance);

                PivotInitialized = true;              
            }

            pvg.CollapseAll();
            pvg.BestFit();
            pvg.Focus();
        }

        void pivotGridControl1_CellClick(object sender, DevExpress.XtraPivotGrid.PivotCellEventArgs e)
        {
            gridControl1.DataSource = e.CreateDrillDownDataSource();
            ExpandCollapse(splitContainerControl1, (gridView1.RowCount > 0 ? AcKapa.Expand : AcKapa.Collapse));
            gridView1.BestFitColumns();
            gridView1.MoveFirst();
        }

        BindingSource bs;
        void pivotGridControl1_CustomAppearance(object sender, PivotCustomAppearanceEventArgs e)
        {
            if (e.Focused)
                e.Appearance.BackColor = e.Appearance.BackColor2 = Color.YellowGreen;   // Color.FromArgb(255, 192, 0);
        }

    }
}
